package com.chenyue.cm;

import com.alibaba.fastjson.JSON;
import com.chenyue.cm.base.bean.PageVo;
import com.chenyue.cm.bean.CodeMakerBean;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.C;
import com.chenyue.cm.common.constant.ConstantValues;
import com.chenyue.cm.common.utils.Freemarker;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;

@Controller
@RequestMapping("/sysCodeMaker")
public class SysCodeMakerController   {
	
	@Resource
    private JdbcTemplate jdbcTemplate;
	
	/**
	 * 显示数据库所有表信息
	 */
	public static final String SHOW_TABLES_MYSQL = "show tables";

	/**
	 * 显示数据表对应所有列信息
	 */
	public static final String SHOW_COLUMNS_MYSQL = "select  * from Information_schema.columns  where table_Name = '${tablename}' and table_schema='jiedengtiyu';  ";
	
	private String page_url_list = "/tools/codeMakerPage";
	
	private String page_result = "common/result";

	/**
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/toList")
	public String toList(HttpServletRequest request, HttpServletResponse response, Model model) {
		return page_url_list;
	}
	
	
	
	
	
	@RequestMapping("/dobuild")
	public String dobuild(HttpServletRequest request, HttpServletResponse response) {

		String projectPath = request.getParameter("projectPath");// 项目所在路径
		String moudule = request.getParameter("mouduleName");// 生成的模块名称
		String tablename = request.getParameter("tablename");// 表名、实体名
		String type = request.getParameter("type");// 0DAO层 1 业务层 2视图层


		// 执行生成方法
		String contextPath = this.getClass().getResource("/").getPath();

		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("vo", getBeanByRequest(request));
		
		
		// pages前置路径
		String pathHtmlString = projectPath + "src/main/resources/templates/" + C.THEME_Prefix +moudule;

		try {

			if ("0".equals(type)) {// DAO层
				
				System.out.println("DAO--------处理成功");
				
			} else if ("1".equals(type)) {// 业务层
				 
				System.out.println("业务层--------处理成功");
			} else if ("2".equals(type)) {// 视图层
				
				String pathListV1 =  pathHtmlString + "/" + underlineToCamel(tablename).toLowerCase() + "/" +  "listPageV1.0.html"  ;
				Freemarker.printFile("listV1.0.ftl", dataMap, pathListV1  , contextPath);
				
				String pathListV3 =  pathHtmlString + "/" + underlineToCamel(tablename).toLowerCase() + "/" +  "listPageV3.0.html"  ;
				Freemarker.printFile("listV3.0.ftl", dataMap, pathListV3, contextPath);

				String pathListPage =  pathHtmlString + "/" + underlineToCamel(tablename).toLowerCase() + "/" + underlineToCamel(tablename) + "List.html"  ;
				Freemarker.printFile("pageList.ftl", dataMap, pathListPage, contextPath);
				
				String pathFormPage =  pathHtmlString + "/" + underlineToCamel(tablename).toLowerCase() + "/" + underlineToCamel(tablename) + "Form.html"  ;
				Freemarker.printFile("pageForm.ftl", dataMap,pathFormPage , contextPath);
				
				System.out.println("视图层--------处理成功");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		// 打包文件
		// FileZip.zip("F://Z", "F://CODE.zip");
		// 下载
		// FileDownload.fileDownload(response, "F://CODE.zip", "code.zip");

		return page_result;
	}

	
	
	
	/**
	 * 获取表名列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getTableList")
	@ResponseBody
	public List<Map<String, Object>> getTableList(HttpServletRequest request, HttpServletResponse response) {

		List<Map<String, Object>> a = jdbcTemplate.queryForList(SHOW_TABLES_MYSQL) ;
		// System.err.println(JSON.toJSONString(a));

		List<Map<String, Object>> resultList = new ArrayList<>();
		for (Map<String, Object> map : a) {
			System.out.println(map);
			for (Entry<String, Object> vo : map.entrySet()) {
				Map<String, Object> mapR = new HashMap<String, Object>();
				mapR.put("tablename", vo.getValue());
				resultList.add(mapR);
			}
		}

		return resultList;
	}

	/**
	 * 
	 * 根据表名 获取列名 列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getColumnList")
	@ResponseBody
	public PageVo<Map<String, Object>> getColumnList(HttpServletRequest request, HttpServletResponse response) {
		String tableNameString = request.getParameter("tablename");
		List<Map<String, Object>> columns = jdbcTemplate.queryForList(SHOW_COLUMNS_MYSQL.replace("${tablename}", tableNameString));
		System.err.println(JSON.toJSONString(columns));
		System.out.println(SHOW_COLUMNS_MYSQL.replace("${tablename}", tableNameString));
		for (Map<String, Object> map : columns) {
			map.put("ELEMENT_TYPE", "0");
			map.put("ISSHOW", "1");
			map.put("ISMUST", "1");
		}
		
		
		
		PageVo<Map<String, Object>> a = new PageVo<>(columns, (int) columns.size());
		return a;
	}

	/**
	 * 下划线格式字符串转换为驼峰格式字符串
	 * 
	 * @param param
	 * @return
	 */
	public static String underlineToCamel(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		StringBuilder sb = new StringBuilder(param);
		Matcher mc = ConstantValues.COMPILE_WITH_.matcher(param);
		int i = 0;
		while (mc.find()) {
			int position = mc.end() - (i++);
			sb.replace(position - 1, position + 1, sb.substring(position, position + 1).toUpperCase());
		}
		return sb.toString();
	}
	
	
	
	
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	

	
	/**
	 * 
	 * 代码生成器----预览
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/preview")
	@ResponseBody
	public Success<Map<String, Object>> preview(HttpServletRequest request) {
		
		Map<String, Object> resultPageMap = new HashMap<>();
		// 执行生成方法
		String contextPath = this.getClass().getResource("/").getPath();
		
		System.err.println(contextPath);
		
		
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("vo", getBeanByRequest(request));
		
		String[] tmps = new String[]{"vue.ftl","api.ftl"};
		
		for (String string : tmps) {
			String aString = Freemarker.printTemplate(string, dataMap, contextPath);
			resultPageMap.put(string ,aString );
		}
		
		return Success.success(resultPageMap);
	}





	/**
	 * 
	 * 从请求中解析---生成实体
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private CodeMakerBean getBeanByRequest(HttpServletRequest request) {
		
		
		// 生成的模块名称
		String moudule = request.getParameter("mouduleName");
		// 生成的模块描述
		String describe = request.getParameter("describe");
		// 传输的配置信息
		String dataString = request.getParameter("data");
		// 表名、实体名
		String tablename = request.getParameter("tablename");

		//数据库字段封装
		List<Object> list = JSON.parseArray(dataString);
		List<Map<String, Object>> columnlist = new ArrayList<Map<String, Object>>();
		for (Object object : list) {
			Map<String, Object> map = (Map<String, Object>) object;
			columnlist.add(map);
		}
		System.err.println(JSON.toJSONString(columnlist));

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("moudule", describe);// 所属父模块
		paramMap.put("describe", describe);// 模块描述
		
		CodeMakerBean cmb = new CodeMakerBean(tablename, paramMap, columnlist);
		
		
		return cmb;
	}
	
	
	
	
	 
	
	
	
}
